﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExtAspNet;
using Helper.Bussiness;
using com.SEO.Model;
using System.Transactions;

namespace SEO_Server.Pages.Rank
{
    public partial class KeywordSettingPage : System.Web.UI.Page
    {
        /// <summary>
        /// SiteID
        /// </summary>
        public string SiteID
        {
            get
            {
                if (ViewState["SiteID"] == null)
                {
                    return null;
                }

                return (string)ViewState["SiteID"];
            }
            set
            {
                ViewState["SiteID"] = value;
            }
        }

        public int LastFormIndex
        {
            get
            {
                if (ViewState["LastFormIndex"] == null)
                {
                    return 1;
                }

                return (int)ViewState["LastFormIndex"];
            }
            set
            {
                ViewState["LastFormIndex"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SiteID = Request.QueryString["SiteID"];
                LastFormIndex = 1;
                BindExistsKeywords();
            }
            else
            {
                if (Request.Form["__EVENTTARGET"] == "pelMain$GroupPanel2$Toolbar1$btnGoOn")
                {
                    LastFormIndex += 1;
                }

                for (int i = 1; i < LastFormIndex; i++)
                {
                    FormRow newFormRow = new FormRow();
                    newFormRow.ID = "FormRow" + (i + 1);
                    newFormRow.ColumnWidths = "20% 20% 20% 20% 20%";

                    ExtAspNet.TextBox textBox = null;
                    for (int j = 1; j < 6; j++)
                    {
                        textBox = new ExtAspNet.TextBox();
                        textBox.ID = "btn" + newFormRow.ID + j;
                        textBox.ShowLabel = false;
                        textBox.MaxLength = 50;
                        textBox.MaxLengthMessage = "關鍵字長度不可超過50!";

                        newFormRow.Items.Add(textBox);
                    }

                    frmKeyword.Rows.Add(newFormRow);
                }
            }
        }

        #region Private Methods

        private void BindExistsKeywords()
        {
            if (SiteID == null)
                return;

            KeywordManage keywordManage = new KeywordManage();
            List<KeywordInfo> lstKeyword = keywordManage.GetKeywordInfoByCondition(" SiteID = '" + SiteID + "' order by Keyword asc");
            foreach (KeywordInfo info in lstKeyword)
            {
                lblKeywords.Text += (lblKeywords.Text.Trim().Length == 0 ? "" : " ") + info.Keyword;
            }
        }

        #endregion

        #region Page Event

        /// <summary>
        /// Close Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(ExtAspNet.ActiveWindow.GetHidePostBackReference());
        }

        /// <summary>
        /// Save Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEnter_Click(object sender, EventArgs e)
        {
            KeywordManage keywordManage = new KeywordManage();
            KeywordInfo keywordInfo = null;
            int transactionResult = 0;

            // Check the keyword is aleady exists or not.
            // If it's exists, then alert to user.
            foreach (FormRow row in frmKeyword.Rows)
            {
                foreach (var item in row.Items)
                {
                    if (item is ExtAspNet.TextBox)
                    {
                        string strKeyword = ((ExtAspNet.TextBox)item).Text.Trim();

                        if (strKeyword.Length > 0)
                        {
                            List<KeywordInfo> lstKeywordInfo = keywordManage.GetKeywordInfoByCondition(" Keyword = '" + strKeyword
                                + "' and SiteID = '" + SiteID + "'");
                            if (lstKeywordInfo.Count > 0)
                            {
                                Alert.Show("關鍵字: " + strKeyword + " 已存在!");
                                return;
                            }
                        }
                    }
                }
            }

            // Use the transaction to insert the keywords into DB, if there has any
            // exception throws, then roll back.
            TransactionOptions transactionOperation = new TransactionOptions();
            transactionOperation.IsolationLevel = IsolationLevel.ReadCommitted;
            int result;
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOperation))
            {
                foreach (FormRow row in frmKeyword.Rows)
                {
                    foreach (var item in row.Items)
                    {
                        if (item is ExtAspNet.TextBox)
                        {
                            string strKeyword = ((ExtAspNet.TextBox)item).Text.Trim();
                            if (strKeyword.Length > 0)
                            {
                                keywordInfo = new KeywordInfo();
                                keywordInfo.KeywordId = Guid.NewGuid();
                                keywordInfo.SiteId = new Guid(SiteID);
                                keywordInfo.Keyword = strKeyword;

                                result = keywordManage.AddkeywordInfo(keywordInfo);
                                if (result != -1)
                                {
                                    transactionResult = 1;
                                }
                            }
                        }
                    }
                }

                transactionScope.Complete();
            }

            if (transactionResult == 1)
            {
                Alert.Show("設置關鍵字失敗!");
                return;
            }
            else
            {
                this.btnClose_Click(null, null);
            }
        }

        protected void btnGoOn_Click(object sender, EventArgs e)
        {

        }

        #endregion
    }
}